<template>
  <div class="map-container">
    <!-- 地图容器 -->
    <div id="mapContainer" class="map"></div>

    <!-- 输入目的地 -->
    <div class="input-group">
      <el-input v-model="destination" placeholder="请输入目的地地址" />
      <el-button type="primary" @click="startNavigation">开始导航</el-button>
    </div>

    <!-- 显示定位信息 -->
    <div v-if="locationInfo" class="location-info">
      <p>当前位置：{{ locationInfo.lng }}, {{ locationInfo.lat }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import axios from 'axios'

const map = ref(null)
const locationInfo = ref(null)
const destination = ref('')
const userLocation = ref([116.397428, 39.90923]) // 默认北京坐标

// 初始化地图
const initMap = async () => {
  try {
    const AMap = await AMapLoader.load({
      key: '你的高德地图Key', // 替换为你的 API Key
      version: '2.0',
      plugins: ['AMap.Geolocation', 'AMap.Driving'] // 加载定位和路径规划插件
    })
    map.value = new AMap.Map('mapContainer', {
      zoom: 15,
      center: userLocation.value
    })

    // 自动定位用户位置
    const geolocation = new AMap.Geolocation({
      enableHighAccuracy: true,
      timeout: 10000,
      zoomToAccuracy: true
    })
    map.value.addControl(geolocation)

    geolocation.getCurrentPosition((status, result) => {
      if (status === 'complete') {
        const position = result.position
        userLocation.value = [position.lng, position.lat]
        locationInfo.value = { lng: position.lng, lat: position.lat }
        map.value.setCenter(userLocation.value)
        addMarker(userLocation.value, '当前位置')
      } else {
        alert('定位失败，请检查网络或权限设置')
      }
    })
  } catch (error) {
    console.error('地图初始化失败:', error)
    alert('地图加载失败，请检查 API Key 或 网络连接')
  }
}

// 添加标记
const addMarker = (position, title) => {
  const marker = new AMap.Marker({
    position: position,
    title: title,
    map: map.value
  })
  return marker
}

// 地址解析为经纬度
const getCoordinates = async (address) => {
  try {
    const response = await axios.get(
        'https://restapi.amap.com/v5/geocode/geo',
        {
          params: {
            key: '你的高德地图Key', // 替换为你的 API Key
            address: address
          }
        }
    )
    if (response.data.status === '1' && response.data.geocodes.length > 0) {
      const { location } = response.data.geocodes[0]
      return location.split(',')
    } else {
      alert('无法解析该地址')
      return null
    }
  } catch (error) {
    console.error('地址解析失败:', error)
    alert('地址解析失败，请检查输入内容')
    return null
  }
}

// 开始导航
const startNavigation = async () => {
  if (!destination.value) {
    alert('请输入目的地')
    return
  }

  const destinationCoords = await getCoordinates(destination.value)
  if (!destinationCoords) return

  // 路径规划
  const driving = new AMap.Driving({
    map: map.value,
    panel: 'panel'
  })
  driving.search(
      new AMap.LngLat(...userLocation.value),
      new AMap.LngLat(...destinationCoords),
      (status, result) => {
        if (status === 'complete') {
          console.log('路径规划完成')
        } else {
          alert('路径规划失败，请重试')
        }
      }
  )

  // 添加目的地标记
  addMarker(destinationCoords, '目的地')
}

// 组件挂载时初始化地图
onMounted(() => {
  initMap()
})
</script>

<style scoped>
.map-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.map {
  flex: 1;
  width: 100%;
}

.input-group {
  display: flex;
  margin: 10px;
  gap: 10px;
}

.location-info {
  margin: 10px;
  background: #f0f0f0;
  padding: 10px;
  border-radius: 5px;
}
</style>